package impl

import (
	"context"
	"fmt"

	"gitee.com/go-course/go8/projects/devcloud/mcenter/apps/notify"
	"gitee.com/go-course/go8/projects/devcloud/mcenter/apps/notify/provider/sms"
	"gitee.com/go-course/go8/projects/devcloud/mcenter/apps/notify/provider/sms/tencent"
	"gitee.com/go-course/go8/projects/devcloud/mcenter/apps/user"
	"github.com/caarlos0/env/v6"
)

// 短信通知
func (s *service) SendSMS(ctx context.Context, req *notify.SendSMSRequest) (*notify.SendSmsResponse, error) {
	// 查询用户电话号码, 构造短信发送请求
	sendReq := sms.NewSendSMSRequest()
	sendReq.TemplateId = req.TemplateId
	sendReq.TemplateParams = req.TemplateParams

	// 查询用户的电话号码
	for i := range req.Users {
		u, err := s.user.DescribeUser(ctx, user.NewDescriptUserRequestWithName(req.Users[i]))
		if err != nil {
			return nil, fmt.Errorf("get user error, %s", err)
		}
		if u.Profile.Phone != "" {
			sendReq.AddPhone(u.Profile.Phone)
		}
	}

	// 短信通知的配置通过环境变量读取(自己放到配置文件中去)
	conf := &tencent.Config{}
	if err := env.Parse(conf); err != nil {
		panic(err)
	}

	// 基于Tencent云的 短信通知服务
	sender, err := tencent.NewSender(conf)
	if err != nil {
		return nil, err
	}
	if err := sender.Send(ctx, sendReq); err != nil {
		return nil, err
	}

	resp := &notify.SendSmsResponse{
		SuccessedNumbers: sendReq.PhoneNumbers,
	}

	return resp, nil
}
